package com.qfmy.mystation.ui.fragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Interpolator;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.view.ViewCompat;
import androidx.core.view.ViewPropertyAnimatorListener;
import androidx.fragment.app.Fragment;
import androidx.interpolator.view.animation.FastOutSlowInInterpolator;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.qfmy.mystation.R;
import com.qfmy.mystation.api.APIService;
import com.qfmy.mystation.bean.LiveWallpaperBean;
import com.qfmy.mystation.bean.WallpaperBean;
import com.qfmy.mystation.databinding.FragmentItemBinding;
import com.qfmy.mystation.ui.adapter.ImageListAdapter;
import com.qfmy.mystation.ui.adapter.LiveWallpaperAdapter;
import com.qfmy.mystation.utils.Constants;
import com.qfmy.mystation.utils.ResUtils;
import com.qfmy.mystation.utils.RxSchedulers;
import com.qfmy.mystation.utils.ToastUtils;

import java.util.ArrayList;

import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.CompositeDisposable;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

public class ItemFragment extends Fragment {
    private int mCurPage = 1;
    private int total_count = 0;
    private CompositeDisposable mSubscriptions;
    private ImageListAdapter mAdapter;
    private LiveWallpaperAdapter liveWallpaperAdapter;
    private final Interpolator INTERPOLATOR = new FastOutSlowInInterpolator();
    private ArrayList<WallpaperBean> wallpaperList;
    private ArrayList<LiveWallpaperBean.DataDTO.ListDTO> liveWallpaperList;
    private String name;
    private int type;

    private FragmentItemBinding binding;

    public static ItemFragment newInstance(String name, int type) {
        ItemFragment fragment = new ItemFragment();
        fragment.name = name;
        fragment.type = type;
        return fragment;
    }

    public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentItemBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        binding.rvWallpaper.setLayoutManager(new GridLayoutManager(getActivity(), 2));
        if (type == Constants.STATIC_WALLPAPER) {
            mAdapter = new ImageListAdapter(getContext(), wallpaperList);
            binding.rvWallpaper.setAdapter(mAdapter);
            binding.srlRefresh.setOnRefreshListener(() -> {
                mCurPage = 1;
                fetchGankMZ(true);
            });
        } else if (type == Constants.LIVE_WALLPAPER) {
            liveWallpaperAdapter = new LiveWallpaperAdapter(getContext(), liveWallpaperList);
            binding.rvWallpaper.setAdapter(mAdapter);
            binding.srlRefresh.setOnRefreshListener(() -> {
                mCurPage = 1;
                getLiveWallpaper(true);
            });
        }
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);

        binding.rvWallpaper.addOnScrollListener(new RecyclerView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
                LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
                if (newState == RecyclerView.SCROLL_STATE_IDLE) {//加载更多
                    assert layoutManager != null;
                    if (layoutManager.getItemCount() - recyclerView.getChildCount() <= layoutManager.findFirstVisibleItemPosition()) {
                        ++mCurPage;
                        if (type == Constants.STATIC_WALLPAPER) {
                            fetchGankMZ(false);
                        } else if (type == Constants.LIVE_WALLPAPER) {
                            getLiveWallpaper(false);
                        }
                    }
                }
                assert layoutManager != null;
                if (layoutManager.findFirstVisibleItemPosition() != 0) {
                    fabInAnim();
                } else {
                    fabOutAnim();
                }
            }
        });
        binding.fabTop.setOnClickListener(v -> {
            LinearLayoutManager manager = (LinearLayoutManager) binding.rvWallpaper.getLayoutManager();
            //如果超过50项直接跳到开头，不然要滚好久
            assert manager != null;
            if (manager.findFirstVisibleItemPosition() < 50) {
                binding.rvWallpaper.smoothScrollToPosition(0);
            } else {
                binding.rvWallpaper.scrollToPosition(0);
                fabOutAnim();
            }
        });
        return root;
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        mSubscriptions = new CompositeDisposable();
        if (type == Constants.STATIC_WALLPAPER) {
            wallpaperList = new ArrayList<>();
            mAdapter = new ImageListAdapter(getActivity(), wallpaperList);
            binding.rvWallpaper.setAdapter(mAdapter);
        } else if (type == Constants.LIVE_WALLPAPER) {
            liveWallpaperList = new ArrayList<>();
            liveWallpaperAdapter = new LiveWallpaperAdapter(getActivity(), liveWallpaperList);
            binding.rvWallpaper.setAdapter(liveWallpaperAdapter);
        }
        binding.srlRefresh.setRefreshing(true);
        if (type == Constants.STATIC_WALLPAPER) {
            fetchGankMZ(true);
        } else if (type == Constants.LIVE_WALLPAPER) {
            getLiveWallpaper(true);
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }

    private void fetchGankMZ(boolean isRefresh) {
        Disposable subscribe = APIService.getInstance().apis.getWallpaperByCategory(mCurPage, name, 18)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(subscription -> binding.srlRefresh.setRefreshing(true))
                .doFinally(() -> binding.srlRefresh.setRefreshing(false))
                .subscribe(data -> {
                    if (data != null && data.getData() != null && data.getData().getList().size() > 0) {
                        ArrayList<WallpaperBean> results = data.getData().getList();
                        if (isRefresh) {
                            total_count = data.getData().getTotal_count();
                            mAdapter.addAll(results);
                            ToastUtils.shortToast(ResUtils.getString(R.string.refresh_success));
                        } else if (wallpaperList.size() < total_count) {
                            mAdapter.loadMore(results);
                            String msg = String.format(ResUtils.getString(R.string.load_more_num), results.size(), "壁纸");
                            ToastUtils.shortToast(msg);
                        } else {
                            ToastUtils.shortToast("已经到底啦！！！");
                        }
                    }
                }, RxSchedulers::processRequestException);
        mSubscriptions.add(subscribe);
    }

    private void getLiveWallpaper(boolean isRefresh) {
        Disposable subscribe = APIService.getInstance().apis.getLiveWallpaperByCategory(mCurPage, name, 18)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .doOnSubscribe(subscription -> binding.srlRefresh.setRefreshing(true))
                .doFinally(() -> binding.srlRefresh.setRefreshing(false))
                .subscribe(data -> {
                    if (data != null && data.getData() != null && data.getData().getList().size() > 0) {
                        ArrayList<LiveWallpaperBean.DataDTO.ListDTO> results = data.getData().getList();
                        if (isRefresh) {
                            total_count = data.getData().getTotal_count();
                            liveWallpaperAdapter.addAll(results);
                            ToastUtils.shortToast(ResUtils.getString(R.string.refresh_success));
                        } else if (liveWallpaperList.size() < total_count) {
                            liveWallpaperAdapter.loadMore(results);
                            String msg = String.format(ResUtils.getString(R.string.load_more_num), results.size(), "壁纸");
                            ToastUtils.shortToast(msg);
                        } else {
                            ToastUtils.shortToast("已经到底啦！！！");
                        }
                    }
                }, RxSchedulers::processRequestException);
        mSubscriptions.add(subscribe);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mSubscriptions.clear();
    }

    /* 悬浮按钮显示动画 */
    private void fabInAnim() {
        if (binding.fabTop.getVisibility() == View.GONE) {
            binding.fabTop.setVisibility(View.VISIBLE);
            ViewCompat.animate(binding.fabTop).scaleX(1.0F).scaleY(1.0F).alpha(1.0F).setInterpolator(INTERPOLATOR).withLayer().setListener(null).start();
        }
    }

    /* 悬浮图标隐藏动画 */
    private void fabOutAnim() {
        if (binding.fabTop.getVisibility() == View.VISIBLE) {
            ViewCompat.animate(binding.fabTop).scaleX(0.0F).scaleY(0.0F).alpha(0.0F).setInterpolator(INTERPOLATOR).withLayer().setListener(new ViewPropertyAnimatorListener() {
                @Override
                public void onAnimationStart(View view) {
                }

                @Override
                public void onAnimationEnd(View view) {
                    binding.fabTop.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationCancel(View view) {
                }
            }).start();
        }
    }
}